package middleware

import (
	"net/http"
	"strings"

	"gitee.com/zoneaurora/shop/internal/common"
	"gitee.com/zoneaurora/shop/internal/model"

	"github.com/gin-gonic/gin"
)

func AuthUser[T model.User | model.AdminUser]() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求头
		tokenString := c.GetHeader("Authorization")

		// 验证token格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			common.JSON(c, http.StatusUnauthorized, "权限不足", nil)
			c.Abort()
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			common.JSON(c, http.StatusUnauthorized, "权限不足", nil)
			c.Abort()
			return
		}

		// 通过验证后，获取id
		id := claims.Id

    // 查询是否存在对应用户
    var user T
    db := common.DB()
    if err := db.First(&user, id).Error; err != nil {
			common.JSON(c, http.StatusUnauthorized, "权限不足", nil)
			c.Abort()
			return
    }

		c.Set("user", user)
		c.Next()
	}
}
